package games.ninJumpDx.ui.actions
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import games.ninJumpDx.data.GameData;
	import games.ninJumpDx.data.UIConfig;
	import games.ninJumpDx.tools.Tools;
	
	import utils.Cartoon;

	public class Score extends Cartoon
	{
		private var m_width:Number;
		private var m_height:Number;
		
		private var m_score:Sprite;
		private var m_nums:Vector.<BitmapData>;
		
		public function Score() 
		{
			var bg:Bitmap = Tools.getBitmapByName("score_bar",GFrame.MAIN_UI);
			UIConfig.setCenterX(bg);
			bg.y = UIConfig.getInfoByName("score_bar").@y;
			addChild(bg);
			
			m_score = new Sprite();
			addChild(m_score);
			var bmd:BitmapData = Tools.getBitmapDataByName("digits",GFrame.MAIN_UI);
			m_width = bmd.width / 10;
			m_height = bmd.height;
			m_nums = new Vector.<BitmapData>();
			var bmdCopy:BitmapData;
			bmd.lock();
			for(var i:int = 0; i < 10; i++)
			{
				bmdCopy = new BitmapData(m_width,m_height,true,0xFFFFFF);
				bmdCopy.lock();
				bmdCopy.copyPixels(bmd,new Rectangle(i * m_width,0,m_width,m_height),new Point(0,0));
				bmdCopy.unlock();
				m_nums.push(bmdCopy);
			}
			bmd.unlock();
			bmd.dispose();
		}
		
		override public function update(t:Object=null):void
		{
			if(!start || pause)return;
			clear();
			showScore(GameData.instance.score);
		}
		
		private function showScore(n:int):void
		{
			
			var score:String = n.toString();
			var a:Array = score.split("");
			for(var i:int = 0; i < a.length; i++)
			{
				drawNumber(int(a[i]),i * (m_width + 2),0);
			}
			
			UIConfig.setCenter(m_score);
			m_score.y = 12;
		}
		
		private function drawNumber(num:int,x:Number,y:Number):void
		{
			/*m_bmd.lock();
			m_bmdCopy = new BitmapData(m_width,m_height,true,0xFFFFFF);
			m_bmdCopy.lock();
			m_bmdCopy.copyPixels(m_bmd,new Rectangle(num * m_width,0,m_width,m_height),new Point(0,0));
			m_bmdCopy.unlock();
			m_bmd.unlock();*/
			var bm:Bitmap = new Bitmap(m_nums[num].clone());
			
			//bm.smoothing = true;
			m_score.addChild(bm);
			bm.x = x;
			bm.y = y;
			
		}
		
		private function clear():void
		{
			while(m_score.numChildren > 0)
			{
				var mc:Bitmap = Bitmap(m_score.removeChildAt(0));
				mc.bitmapData.dispose();
			}
		}
		
	}
}